import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:village_android/common/NoKeyboardEditableTextFocusNode.dart';
import 'package:village_android/component/images_collection.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/config/service_method.dart';
import 'package:village_android/model/dept_model.dart';
import 'package:village_android/model/sys_config_model.dart';
import 'package:village_android/model/user_model.dart';
import 'package:village_android/pages/user/user_list.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';
import 'package:village_android/utils/store_utils.dart';
import 'dart:convert' as convert;
import 'package:quiver/strings.dart';

class MonitorReportManagerPage extends StatefulWidget {
  
  
  
  @override
  _MonitorReportManagerPageState createState() =>
      new _MonitorReportManagerPageState();
}

class _MonitorReportManagerPageState extends State<MonitorReportManagerPage> {
  final _formKey = GlobalKey<FormState>();

  String _userId;
  String _name;
  String _address;
  String _phone;
  String _content;
  String _medias = "";

  List sysConfigList = [];
  SysConfigModel curSysConfig;

//sysConfig/list?dictTypeId=11
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('管理员监督-手动填写地址'),
      ),
      body: networkWidget(),
      bottomNavigationBar: initBottom(),
    );
  }

  Widget localWidget() {
    return Container(
      padding: EdgeInsets.all(15),
      child: Form(
        key: _formKey,
        child: ListView(
          children: <Widget>[
            initLoginName(),
            initAddress(),
            initPhone(),
            initEvents(),
            initContent(),
            SizedBox(height: 10.0),
            Text(
              "上传图片",
              style: TextStyle(color: Colors.red),
            ),
            SizedBox(height: 10.0),
            initMutilImages(),
            SizedBox(height: 50.0),
          ],
        ),
      ),
    );
  }

  Widget networkWidget() {
    return FutureBuilder(
        future: getSysConfigList(14),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<SysConfigModel> sysConfigListM = [];
            var data = snapshot.data;
            if (data != null && (data is List)) {
              for (int i = 0; i < data.length; i++) {
                SysConfigModel sysConfigModel =
                    SysConfigModel.fromJson(data[i]);
                sysConfigListM.add(sysConfigModel);
              }
            }
            sysConfigList = sysConfigListM;
          }
          return localWidget();
        });
  }

  Padding initHorizontalLine() {
    return Padding(
        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            color: Colors.deepOrange,
            width: 100,
            height: 2,
          ),
        ));
  }

  TextField initLoginName() {

    return TextField(
      controller: TextEditingController()
        ..text = _name,
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() async {

        var page = UserListPage(deptId: 25,);
        var result = await Navigator.push(context, new MaterialPageRoute(builder: (context) => page));
        if(result!=null){
          UserModel user = result as UserModel;
          setState(() {
            _name = user.account + '-' + user.name ;
            _address = user.address;
            _phone = user.phone;
            _userId = user.userId.toString();
          });
        }
       }),
      decoration: new InputDecoration(labelText: '真实姓名'),
      onChanged: (value) {},
    );

  }

  TextField initAddress() {
    return TextField(
      controller: TextEditingController()
        ..text = _address,
      decoration: new InputDecoration(labelText: '地址', hintText: '如：大学城1号'),
    );
  }

  TextField initEvents() {
    return TextField(
      controller: TextEditingController()
        ..text = curSysConfig != null ? curSysConfig.name : "",
      focusNode: NoKeyboardEditableTextFocusNode(),
      onTap: (() {
        showEventAlertDialog();
      }),
      decoration: new InputDecoration(labelText: '扣分事项', hintText: '如：垃圾太多'),
      onChanged: (value) {},
    );
  }

  TextField initPhone() {
    return TextField(
      controller: TextEditingController()
        ..text = _phone,
      decoration: new InputDecoration(labelText: '手机/电话', hintText: '如：13800000000'),
    );
  }


  TextFormField initContent() {
    return TextFormField(
      onSaved: (String value) => _content = value,
      decoration: InputDecoration(labelText: '扣分内容'),
//      validator: (String value) {
//        if (value == '') {
//          return '户代表不能为空';
//        }
//      },
    );
  }

  //扣分事项
  void showEventAlertDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('选择扣分事项'),
          children: getRadioList(),
        );
      },
    ).then((val) {});
  }

  List<Widget> getRadioList() {
    List<RadioListTile<SysConfigModel>> radioList = [];
//    SysConfigModel _newValue = curSysConfig !=null ? curSysConfig :sysConfigList[0];
    for (int i = 0; i < sysConfigList.length; i++) {
      SysConfigModel sysConfigModel = sysConfigList[i];
      RadioListTile listTile = RadioListTile<SysConfigModel>(
        value: sysConfigModel,
        title: Text(sysConfigModel.name),
        groupValue: null,
        onChanged: (value) {
          SysConfigModel newModel = value;
          setState(() {
            curSysConfig = newModel;
          });
//          _deptId = value;

          Navigator.of(context).pop();
        },
      );
      radioList.add(listTile);
    }
    return radioList;
  }

  Widget initMutilImages() {

    return ImagesCollectionPage(
      items: [],
      itemsCallBack: ((items) {
        List medias = items as List;
        String mediasString = "";
        for (var i = 0; i < medias.length; i++) {
          if (i > 0) {
            mediasString = mediasString +
                (mediasString.length == 0 ? "" : ",") +
                medias[i];
          }
        }
        _medias = mediasString;
        print(_medias);
      }),
    );
  }

  Widget initBottom() {
    return BottomAppBar(
        child: Row(
          children: <Widget>[
            Expanded(
                child: JdButton(
                  callBack: () {
                    //CommonUtils.showToast(context, '登录');
                    //CommonUtils.showToast(context, '登录');
                    if (_formKey.currentState.validate()) {
                      _formKey.currentState.save();
                      showAlertDialog();
                    }
                  },
                  text: "确定",
                  color: Colors.red,
                )),
          ],
        ));
  }


  void showAlertDialog() {

    var userName = CommonUtils.getUsername();


    if (isEmpty(userName)) {
      CommonUtils.showToast(context, "请重新登录");
      return;
    }

    if (isEmpty(_name)) {
      CommonUtils.showToast(context, "请填写名字");
      return;
    }
    if (isEmpty(_phone)) {
      CommonUtils.showToast(context, "请填写手机");
      return;
    }
    if (isEmpty(_address)) {
      CommonUtils.showToast(context, "请填写地址");
      return;
    }
    if (isEmpty(_content)) {
      CommonUtils.showToast(context, "请填写扣分内容");
      return;
    }
    if (curSysConfig == null) {
      CommonUtils.showToast(context, "请选择扣分事项");
      return;
    }

    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("是否提交"),
                content: new Text(""),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      toDone();
                    },
                  )
                ]));
  }

  Future toDone() async {

    //数据处理
    List items=_medias.split(",");
    var coverUrl=items[0];
    var userName = CommonUtils.getUsername();


    FormData formData = new FormData.from({
      "address": _address,
      "phone": _phone,
      "username": _name,
      "targetUserId": _userId,
      "content": _content,
      "events": curSysConfig.code,
      "medias": _medias,
      "coverUrl": coverUrl,
      "reportUserName":userName
    });
//    var dio = new Dio();
//    var response =
//        await dio.post(BaseUrl.url + "/mgr/register", data: formData);
//    print(response.data.toString());
//
//    var data = response.data;

    HttpUtils.postForm("/api/healthReport/addItem", formData: formData,
        success: (data) {
      CommonUtils.showToast(context, "新增成功");
      new Future.delayed(
          const Duration(seconds: 1), () => {Navigator.of(context).pop()});
    }, error: (errorMsg) {
      CommonUtils.showToast(context, errorMsg);
    });
  }
}
